/*
 *  Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com).
 *  <p>
 *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  <p>
 * https://www.gnu.org/licenses/lgpl.html
 *  <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sofa.shark.common.log.apm.aspect;


import com.sofa.shark.common.core.utils.SpringContextHolder;
import com.sofa.shark.common.log.apm.annotation.SysLog;
import com.sofa.shark.common.log.apm.event.SysLogEvent;
import com.sofa.shark.common.log.apm.logfactory.Apm;
import com.sofa.shark.common.log.apm.logfactory.ApmMetrics;
import com.sofa.shark.common.log.apm.util.SysLogUtils;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * 操作日志使用spring event异步入库
 *
 * @author tonyp
 * @version 1.0.0
 * @date 2020.3.31
 */
@Aspect
public class SysLogAspect {

    @Around("@annotation(sysLog)")
    @SneakyThrows
    public Object around(ProceedingJoinPoint point, SysLog sysLog) {
        String strClassName = point.getTarget().getClass().getName();
        String strMethodName = point.getSignature().getName();
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SysLog webLog = method.getAnnotation(SysLog.class);
        if (webLog == null) {
            // 获取类上的注解
            webLog = point.getTarget().getClass().getAnnotation(SysLog.class);
        }
        String priority = webLog.priority();
        String tag = webLog.tag();
        String value = webLog.value();
        // 接收到请求，记录请求内容
        Object obj = null;
        ApmMetrics apmMetrics = Apm.begin(strClassName, strMethodName);
        try {
            com.sofa.shark.admin.api.entity.SysLog syslogVo = SysLogUtils.getSysLog();
            syslogVo.setTitle(strMethodName);
            syslogVo.setType(priority);
            obj = point.proceed();
            SpringContextHolder.publishEvent(new SysLogEvent(syslogVo));
        } catch (Exception ex) {
            apmMetrics.error(ex);
        }
        apmMetrics.end();
        return obj;
    }
}
